﻿using DBPOIGET.Classes;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace DBPOIGET
{
    public partial class FormMain : Form
    {
        internal readonly GMapOverlay poiobjects = new GMapOverlay("objects");

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            tscb_coord.SelectedIndex = 0;
            MapControl.Manager.Mode = AccessMode.ServerAndCache;
            MapControl.MapProvider = GMapProviders.OpenStreetMap;
            MapControl.Position = new PointLatLng(30.6, 114.3);
            MapControl.MinZoom = 0;
            MapControl.MaxZoom = 24;
            MapControl.Zoom = 9;
            MapControl.DisableAltForSelection = true;
            MapControl.Overlays.Add(poiobjects);
        }

        private void tsbtn_download_Click(object sender, EventArgs e)
        {
            if (MapControl.SelectedArea.IsEmpty)
            {
                MessageBox.Show("请在地图上选择要下载的范围", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (tstb_keyword.Text == string.Empty)
            {
                MessageBox.Show("请输入搜索关键字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (tstb_ak.Text == string.Empty)
            {
                MessageBox.Show("请输入百度地图网页API密钥", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            CoordinateType type = CoordinateType.WGS_84;
            switch (tscb_coord.SelectedIndex)
            {
                case 0:
                    type = CoordinateType.WGS_84;
                    break;
                case 1:
                    type = CoordinateType.GCJ_02;
                    break;
                case 2:
                    type = CoordinateType.BD_90;
                    break;
                default:
                    break;
            }

            poiobjects.Clear();
            POIs.poidic.Clear();

            bool running = true;
            FormProcess fmProcess = new FormProcess();

            Thread t = new Thread(() => {
                var r = MapControl.SelectedArea;
                var top = r.Top;
                var bottom = r.Bottom;
                var left = r.Left;
                var right = r.Right;
                Coordinate c1 = new Coordinate(left, top, CoordinateType.WGS_84);
                c1.ToBD();
                Coordinate c2 = new Coordinate(right, bottom, CoordinateType.WGS_84);
                c2.ToBD();
                left = c1.Longitude;
                right = c2.Longitude;
                top = c1.Latitude;
                bottom = c2.Latitude;
                //要将一个大范围分成好多个小范围来下载，目前以百分之一度来分
                var wCount = Convert.ToInt32((right - left) * 100) + 1;
                var hCount = Convert.ToInt32((top - bottom) * 100) + 1;
                int wIndex = 0, hIndex = 0;
                for (int i = 0; i < wCount && running; i++)
                {
                    var llng = left + i * 0.01;
                    var rlng = llng + 0.01;
                    rlng = rlng > right ? right : rlng;
                    for (int j = 0; j < hCount && running; j++)
                    {
                        var blat = bottom + j * 0.01;
                        var tlat = blat + 0.01;
                        tlat = tlat > top ? top : tlat;
                        POIs pois = new POIs();
                        pois.OnePoiDownloaded += (send, arg) =>
                        {
                            fmProcess.setCount(POIs.poidic.Count);
                        };
                        pois.Init(tstb_keyword.Text, llng, tlat, rlng, blat, tstb_ak.Text, type);
                        hIndex++;
                    }
                    wIndex++;
                }
                //下载完成
                fmProcess.Close2();
                MessageBox.Show("下载完成，点击导出按钮将数据导出", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (POIs.poidic.Count > 1000)
                {
                    if (MessageBox.Show("POI数量过多，显示将花费较长事件，是否显示？", "询问", MessageBoxButtons.YesNo,
                        MessageBoxIcon.Information) == DialogResult.No)
                    {
                        return;
                    }
                }
                //在地图上显示POI
                foreach (var poi in POIs.poidic.Values)
                {
                    var lo = new PointLatLng(poi.location.lat, poi.location.lng);
                    var pmark = new GMapMarkerCircle(lo);
                    pmark.Radius = 10;
                    poiobjects.Markers.Add(pmark);
                }
            });
            t.Start();

            fmProcess.Stopped += (send, arg) =>
            {
                running = false;
                t.Abort();
            };
            fmProcess.ShowDialog();
        }

        //导出
        private void tsbtn_export_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "导出POI";
            sfd.Filter = "csv文件（*.csv）|*.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                Export export = new Export(POIs.poidic);
                export.Save(sfd.FileName);
                MessageBox.Show("导出完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}
